$(document).ready(function(){
  getAllTeacher();
  
});
var isUploadSuccess=-1;

$("#section_grid").bootstrapTable({
  url:"/sectionController/queryAllSection",
  cache:false, 
  striped: true, 
    pagination: true, 
    pageList: [10, 20],
    pageSize: 10,
    pageNumber: 1,
    clickToSelect:true,
    sidePagination: 'client',
    sortable: true,
    sortName: 'seSeq',
    ortOrder: 'desc', 
    showRefresh:true,
    uniqueId:'seId',
    columns: [
          {
              checkbox: true, 
              align: 'center' 
          },{
              field: 'seId', // 要显示数据的字段名称，可以理解为json对象里的key
              title: '章节id', // 表格表头显示文字
              align: 'center', // 左右居中
              valign: 'middle', // 上下居中
              visible: false
          },{
              field: 'seName', 
              title: '章节名称',
              align: 'center',
              valign: 'middle'
          }, {
              field: 'seSeq',
              title: '章节顺序',
              align: 'center',
              valign: 'middle',
              formatter: function (value, row, index) {
                  return '第'+value+'章';
              }
          },{
              field: 'tId', 
              title: '老师id', 
              align: 'center', 
              valign: 'middle',
              visible: false
          }, {
              field: 'tName',
              title: '老师编号',
              align: 'center',
              width: 160, 
              valign: 'middle'
          }, {
              field: 'tNickname',
              title: '上课老师',
              align: 'center',
              width: 160, 
              valign: 'middle'
          }, {
              field: 'tTel',
              title: '电话号码',
              align: 'center',
              width: 160,
              valign: 'middle'
          }, {
              field: 'sePpt',
              title: 'ppt',
              align: 'center',
              valign: 'middle'
          },{
              title: "操作(查看对应视频、作业)",
              align: 'center',
              valign: 'middle',
              width: 160, 
              formatter: function (value, row, index) {
                  row.type="section";

                  return '<button class="btn btn-default btn-sm" onclick="queryVideo(\'' + row.seId + '\',\''+row.seName+'\')"><span class="glyphicon glyphicon-film"></span></button>&nbsp;'
                  +'<button class="btn btn-default btn-sm" onclick="queryHomework(\'' + row.seId + '\',\''+row.seName+'\')"><span class="glyphicon glyphicon-book"></span></button>&nbsp;'
                  +'<button class="btn btn-default btn-sm" data-toggle="modal" data-target="#sectionModal" onclick="editSection(\'' + row.seId + '\')">修改</button>';
              }
          }
      ],
      onLoadError: function(){ 
            console.info("加载数据失败");
      }
});

function queryVideo(seId,seName){
  $("#videoTab .seName").html("章节名称："+seName);
  $("#videoTab .seId").html(seId);
  $("#videoTab .btn-groups").removeClass('hidden');
  $("#video_grid").bootstrapTable('destroy');
  $("#video_grid").bootstrapTable({
    url:"/videoController/queryAllVideo",
    cache:false, 
    method:'post',
    contentType : "application/x-www-form-urlencoded",
    striped: true, 
      pagination: true, 
      pageList: [5, 10],
      pageSize: 5,
      pageNumber: 1,
      clickToSelect:true,
      sidePagination: 'client',
      sortable: true,
      sortName: 'vSeq',
      ortOrder: 'desc', 
      showRefresh:true,
      uniqueId:'vId',
      queryParams: function (params) { 
          return {
              seId: seId// 额外添加的参数
          }
      }, 
      columns: [
            {
                checkbox: true, 
                align: 'center' 
            },{
                field: 'vId', // 要显示数据的字段名称，可以理解为json对象里的key
                title: '视频id', // 表格表头显示文字
                align: 'center', // 左右居中
                valign: 'middle', // 上下居中
                visible: false
            },{
                field: 'seId', // 要显示数据的字段名称，可以理解为json对象里的key
                title: '章节id', // 表格表头显示文字
                align: 'center', // 左右居中
                valign: 'middle', // 上下居中
            },{
                field:  'vName', 
                title: '视频名称',
                align: 'center',
                valign: 'middle'
            },{
                field: 'vSeq', 
                title: '视频顺序',
                align: 'center',
                valign: 'middle'
            },{
                title: "操作",
                align: 'center',
                valign: 'middle',
                width: 160, 
                formatter: function (value, row, index) {
                    row.type="video";
                    return '<button class="btn btn-default btn-sm" data-toggle="modal" data-target="#fileModal" onclick="editResourse(\'' + row.vId + '\',\''+row.type+'\')">修改</button>';
                }
            }
        ],
        formatNoMatches: function(){
          return "该章节没有相应的视频";
        }
  });

}

function queryHomework(seId,seName){
  $("#homeworkTab .seName").html("章节名称："+seName);
  $("#homeworkTab .seId").html(seId);
  $("#homeworkTab .btn-groups").removeClass('hidden');
  $("#homework_grid").bootstrapTable('destroy');
  $("#homework_grid").bootstrapTable({
    url:"/homeworkController/queryHomeworkBySeId",
    cache:false, 
    method:'post',
    contentType : "application/x-www-form-urlencoded",
    striped: true, 
      pagination: true, 
      pageList: [5, 10],
      pageSize: 5,
      pageNumber: 1,
      clickToSelect:true,
      sidePagination: 'client',
      sortable: true,
      sortName: 'hId',
      ortOrder: 'desc', 
      showRefresh:true,
      uniqueId:'hId',
      queryParams: function (params) { 
          return {
              seId: seId// 额外添加的参数
          }
      }, 
      columns: [
            {
                checkbox: true, 
                align: 'center' 
            },{
                field: 'hId', // 要显示数据的字段名称，可以理解为json对象里的key
                title: '作业id', // 表格表头显示文字
                align: 'center', // 左右居中
                valign: 'middle', // 上下居中
                visible: false
            },{
                field: 'seId', // 要显示数据的字段名称，可以理解为json对象里的key
                title: '章节id', // 表格表头显示文字
                align: 'center', // 左右居中
                valign: 'middle', // 上下居中
                visible: false
            },{
                field: 'hName', 
                title: '作业名称',
                align: 'center',
                width: 160, 
                valign: 'middle'
            },{
                field: 'hReleasetime', 
                title: '上传时间',
                align: 'center',
                width: 160, 
                valign: 'middle',
                formatter: function (value, row, index){ // 单元格格式化函数
                    var date=new Date(value);
                    return date.getFullYear() + '-' +(date.getMonth()+1) + "-" + date.getDate() + " " +date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                } 
            },{
                field: 'hModifytime', 
                title: '更新时间',
                align: 'center',
                width: 160, 
                valign: 'middle',
                formatter: function (value, row, index){ // 单元格格式化函数
                    var date=new Date(value);
                    return date.getFullYear() + '-' +(date.getMonth()+1) + "-" + date.getDate() + " " +date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                } 
            },{
                title: "操作",
                align: 'center',
                valign: 'middle',
                width: 160, 
                formatter: function (value, row, index) {
                    row.type="homework";
                    return '<button class="btn btn-default btn-sm" data-toggle="modal" data-target="#fileModal" onclick="editResourse(\'' + row.hId + '\',\''+row.type+'\')">修改</button>';
                }
            }
        ],
        formatNoMatches: function(){
          return "该章节没有相应的作业";
        }
  });

}

function addResource(type){
  $("#fileModal .btn-submit").removeAttr('disabled');
  $("#fileModal .addSubmit").removeClass('hidden');
  $("#fileModal .editSubmit").addClass('hidden');
  $("#fileModal .form-control[name='current']").parent().addClass('hidden');
  if(type=="video"){
    $("#fileModal .form-control[name='docfile']").parent().addClass('hidden');
    $("#fileModal .form-control[name='mp4file']").parent().removeClass('hidden');
    $(".form-control[name='vSeq']").parent().removeClass('hidden');
    $(".form-control[name='type']").val('video');
    $("#fileModalLabel").html("添加视频");
    $(".form-control[name='seId']").val($("#videoTab .seId").html());
  }else if(type=="homework"){
    $("#fileModal .form-control[name='mp4file']").parent().addClass('hidden');
    $("#fileModal .form-control[name='docfile']").parent().removeClass('hidden');
    $(".form-control[name='vSeq']").parent().addClass('hidden');
    $(".form-control[name='type']").val('homework');
    $("#fileModalLabel").html("添加作业");
    $(".form-control[name='seId']").val($("#homeworkTab .seId").html());
  }
  
}

function isNull(modal){
  $(" "+modal+" form :input.required").each(function(){
    var obj=$(this).parent().find('.alarm');
    if($(this).val()==""){
      if(obj.length==0){
        $(this).parent().append("<b style='color:red' class='alarm'>X该字段不能为空!</b>");
      }
    }else{
      $(this).parent().find('.alarm').remove();
    }
  })
  var arr=$(" "+modal+" form .form-group:not(.hidden)").find(".required").filter(function(index) {
    return $(this).val()=="";
  });
  if(arr.length!=0){
    alert("请填入完整信息！");
    return false;
  }else{
    return true;
  }
}

function addResourceSubmit() {

    var params={},url="";
    let start="";
    let end="";
    var type=$("#fileModal .form-control[name='type']").val();
    params.seId=$("#fileModal .form-control[name='seId']").val();
    params.vSeq=$("#fileModal .form-control[name='vSeq']").val();
   
    if(type=="video"){
      url="/videoController/addVideo";
      start=$("#fileModal .form-control[name='mp4file']").val().lastIndexOf('\\');
      end=$("#fileModal .form-control[name='mp4file']").val().indexOf('.'); 
      params.name=$("#fileModal .form-control[name='mp4file']").val().slice(start+1,end);
    }else if(type=="homework"){
      url="/homeworkController/addHomework";
      start=$("#fileModal .form-control[name='docfile']").val().lastIndexOf('\\');
      end=$("#fileModal .form-control[name='docfile']").val().indexOf('.'); 
      params.name=$("#fileModal .form-control[name='docfile']").val().slice(start+1,end);
    }
    if(isNull('#fileModal')){
      $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        contentType : "application/json;charset=utf-8",
        data: JSON.stringify(params),
        success:function(data){
          if(data==1){
            alert("添加成功！");
            resetForm();
            $("#fileModal").modal('hide');
          }else{
            alert("添加失败!");
          }
        }
      });
    }
}

$("#fileModal form input[type='file']").blur(function(){
    let start,end;
    var type=$("#fileModal form input[name='type']").val();
    var seId=$("#fileModal form input[name='seId']").val();
    var url="",name;
    var returnMsg;
    if(type=="video"){
      url="/videoController/isNameExist";
      returnMsg="存在同名视频！";
      start=$("#fileModal .form-control[name='mp4file']").val().lastIndexOf('\\');
      end=$("#fileModal .form-control[name='mp4file']").val().indexOf('.'); 
      name=$("#fileModal .form-control[name='mp4file']").val().slice(start+1,end);
    }else if(type=="homework"){
      url="/homeworkController/isNameExist";
      returnMsg="存在同名作业！"
      start=$("#fileModal .form-control[name='docfile']").val().lastIndexOf('\\');
      end=$("#fileModal .form-control[name='docfile']").val().indexOf('.'); 
      name=$("#fileModal .form-control[name='docfile']").val().slice(start+1,end);
    }
    $.ajax({
      url: url,
      type: 'post',
      data: {
        name: name,
        seId, seId
      },
      contentType : "application/x-www-form-urlencoded",
      success:function(data){
          if(data==1){
            $("#fileModal .btn-submit").attr('disabled',true);
          }else{
            $("#fileModal .btn-submit").removeAttr('disabled');
          }
        }
    });
});

$("#fileModal form input[name='vSeq']").blur(function(){
    var vSeq=$("#fileModal form input[name='vSeq']").val();
    var seId=$("#fileModal form input[name='seId']").val();
    $.ajax({
      url: '/videoController/isSeqExist',
      type: 'post',
      data: {
        vSeq: vSeq,
        seId: seId
      },
      contentType : "application/x-www-form-urlencoded",
      success:function(data){
          if(data==1){
            alert("该顺序已存在!");
            $("#fileModal .btn-submit").attr('disabled',true);
          }else{
            $("#fileModal .btn-submit").removeAttr('disabled');
          }
        }
    });
});


function delResource(type){
  var $gird,id;
  var url="";
  if(type=='video'){
    $gird=$("#video_grid");
    url="/videoController/deleteVideo";
    id="vId";
  }else if(type=='homework'){
    $gird=$("#homework_grid");
    url="/homeworkController/deleteHomework";
    id="hId";
  }
  var arr=$gird.bootstrapTable('getSelections');
  var idArr=[];
  if(arr.length==0){
    alert("请至少选一行数据");
  }else{
    if(confirm("确定删除选中数据吗？")){
        for (var i = 0; i < arr.length; i++) {
          idArr.push(arr[i][id]);
      }
      $.ajax({
        url: url,
        type: 'post',
        dataType : "json",
        contentType : "application/json;charset=utf-8",
        data: JSON.stringify(idArr),
        success:function(data){
          if(data==1){
            alert("删除成功！");
          }else{
            alert("删除失败！");
          }
        }
      });
    } 
    
  }
}

function editResourse(id,type){
  var $gird,rowData;
  $("#fileModal .btn-submit").removeAttr('disabled');
  $("#fileModal .addSubmit").addClass('hidden');
  $("#fileModal .editSubmit").removeClass('hidden');
  $("#fileModal form input[name='id']").val(id);
  $("#fileModal form input[name='type']").val(type);
  $("#fileModal .form-control[name='current']").parent().removeClass('hidden');
  if(type=="video"){
    $("#fileModal .form-control[name='docfile']").parent().addClass('hidden');
    $("#fileModal .form-control[name='mp4file']").parent().removeClass('hidden');
    $("#fileModal .form-control[name='vSeq']").parent().removeClass('hidden');
    $("#fileModalLabel").html("修改视频");
    $gird=$("#video_grid");
    rowData=$gird.bootstrapTable('getRowByUniqueId',id);
    $("#fileModal .form-control[name='current']").val(rowData.vName);
  }else if(type=="homework"){
    $("#fileModal .form-control[name='docfile']").parent().removeClass('hidden');
    $("#fileModal .form-control[name='mp4file']").parent().addClass('hidden');
    $("#fileModal .form-control[name='vSeq']").parent().addClass('hidden');
    $gird=$("#homework_grid");
    $("#fileModalLabel").html("修改作业");
    rowData=$gird.bootstrapTable('getRowByUniqueId',id);
    $("#fileModal .form-control[name='current']").val(rowData.hName);
  }
  $("#fileModal .form-control[name='vSeq']").val(rowData.vSeq);
  $("#fileModal .form-control[name='seId']").val(rowData.seId);
}

function editResourceSubmit(){
  var url="",params={},id;
  var type=$("#fileModal .form-control[name='type']").val();
  var formData=new FormData();
  var isFileExist=-1;
  var file="",fileUrl="";
  if(type=="video"){
    url="/videoController/editVideo";
    start=$("#fileModal .form-control[name='mp4file']").val().lastIndexOf('\\');
    end=$("#fileModal .form-control[name='mp4file']").val().indexOf('.'); 
    name=$("#fileModal .form-control[name='mp4file']").val().slice(start+1,end);
    if($("#mp4file")[0].files.length!=0&&isUploadSuccess==1){
      isFileExist=1;
    }

  }else if(type=="homework"){
    url="/homeworkController/editHomework";
    start=$("#fileModal .form-control[name='docfile']").val().lastIndexOf('\\');
    end=$("#fileModal .form-control[name='docfile']").val().indexOf('.'); 
    name=$("#fileModal .form-control[name='docfile']").val().slice(start+1,end);
    if($("#docfile")[0].files.length!=0&&isUploadSuccess==1){
      isFileExist=1;
    }
  }
  params.id=$("#fileModal form input[name='id']").val();
  params.seId=$("#fileModal form input[name='seId']").val();
  params.vSeq=$("#fileModal form input[name='vSeq']").val();
  if(isFileExist==-1){//没有上传资源
    $.ajax({
      url:url,
      type: 'POST',
      dataType: 'json',
      contentType : "application/json;charset=utf-8",
      data: JSON.stringify(params),
      success: function(data){
        if(data==1){
          alert("修改成功！");
          $("#fileModal").modal('hide');
          resetForm();
        }else{
          alert("修改失败！");
        }
      }
    });
  }else{
    if(isUploadSuccess==1){//上传资源成功
      params.name=name;
      $.ajax({
        url:url,
        type: 'POST',
        dataType: 'json',
        contentType : "application/json;charset=utf-8",
        data: JSON.stringify(params),
        success: function(data){
          if(data==1){
            alert("修改成功！");
            $("#fileModal").modal('hide');
            resetForm();
          }else{
            alert("修改失败！");
          }
        }
      });
    }else if(isUploadSuccess==0){
      alert("上传资源失败！");
    }
  }
  
  
  
}

function resetForm(){
  $("form input").each(function(index, el) {
    $(this).parent().find('.alarm').remove();
    $(this).parent().find('.tel').remove();
    $(el).val("");
  });
}

function getAllTeacher(){
  $.ajax({
    url: '/teacherController/queryAllTeacher',
    type: 'POST',
    success: function(data){
      var teacherList=data;
      for (var i = 0; i < data.length; i++) {
        $("#sectionModal select[name='tId']").append('<option value="'+data[i].tId+'">'+data[i].tName+' '+data[i].tNickname+'</option>')
      }
    }
  });
}

function editSection(seId){
  
  var rowData=$("#section_grid").bootstrapTable('getRowByUniqueId',seId);
  $("#sectionModal input[name='seId']").val(seId);
  $("#sectionModal input[name='seName']").val(rowData.seName);
  $("#sectionModal input[name='seSeq']").val(rowData.seSeq);
  $("#sectionModal select[name='tId']").val(rowData.tId);
  $("#sectionModal input[name='sePpt']").val(rowData.sePpt);
}

$("#sectionModal .btn-submit").click(function(event) {
    var params={};
    var start=$("#sectionModal .form-control[name='pptfile']").val().lastIndexOf('\\');
    var end=$("#sectionModal .form-control[name='pptfile']").val().indexOf('.'); 
    var ppt=$("#sectionModal .form-control[name='pptfile']").val().slice(start+1,end);
    params.seName=$("#sectionModal input[name='seName']").val();
    params.seSeq=$("#sectionModal input[name='seSeq']").val();
    params.tId=$("#sectionModal select[name='tId']").val();
    params.seId=$("#sectionModal input[name='seId']").val();
    if(ppt!=""){
      params.sePpt=ppt;
    }
    var formData=new FormData();
    var file=$("#filePPT")[0].files[0];
    formData.append("filePPT",file);
    var isUploadSuccess=-1;
    if($("#filePPT")[0].files.length!=0){
      $.ajax({
        url: '/sectionController/getPPTFile',
        type: 'POST',
        cache:false,
        processData: false,
        data: formData,
        dataType : 'json',
        contentType:false,
        success: function(data){
          if(data.result=="success"){
            isUploadSuccess=1;
          }else{
            isUploadSuccess=0;
          }
        }
      });
    }
    
    if(isUploadSuccess==-1||isUploadSuccess==1){//没有上传ppt
      $.ajax({
        url: '/sectionController/editSection',
        type: 'POST',
        dataType: 'json',
        contentType : "application/json;charset=utf-8",
        data: JSON.stringify(params),
        success: function(data){
          if(data==1){
            alert("修改成功！");
            $("#sectionModal").modal('hide');
          }else{
            alert("修改失败！");
          }
        }
      });
    }else if(isUploadSuccess==0){
      alert("上传ppt失败！");
    }
    
  
})

function upLoadFile(type){
  var file="",fileUrl="";
  
  var formData=new FormData();
  var isExist=-1;
  if(type=="video"){
    file=$("#mp4file")[0].files[0];
    formData.append("file",file);
    fileUrl="/videoController/getVideoFile";
    if($("#mp4file")[0].files.length!=0){
      isExist=1;
    }
  }else if(type=="homework"){
    file=$("#docfile")[0].files[0];
    formData.append("file",file);
    fileUrl="/homeworkController/getHomeworkFile";
    if($("#docfile")[0].files.length!=0){
      isExist=1;
    }
  }
  if(isExist==1){
    alert("上传需要时间比较久，请耐心等待！");
    $.ajax({
      url: fileUrl,
      type: 'POST',
      cache:false,
      processData: false,
      data: formData,
      dataType : 'json',
      contentType:false,
      success: function(data){
        if(data.result=="success"){
          isUploadSuccess=1;
          alert("上传资源成功！");
        }else{
          isUploadSuccess=0;
          alert("上传资源失败！");
        }
      }
    });
  }else{
    alert("请选择要上传的资源！");
  }
}